package com.wys.controller;

import com.wys.result.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 *  文件的上传与下载
 */
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;
    /**
     *  上传文件
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        //file是临时文件，需要进行转出，否则请求完成后会直接删除
        String originalFilename = file.getOriginalFilename();
        //截出文件的后缀属性
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString()+suffix;
        //判断basePath的文件目录是否存在
        File file1=new File(basePath);
        if(!file1.exists()){
            //文件目录不存在
            file1.mkdir();
        }
        try {
            file.transferTo(new File(basePath+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }

    /**
     *  文件下载
     * @param name 要下载的文件名称
     */
    @GetMapping("/download")
    public void downLoad(HttpServletResponse response ,String name){
        try {
            //字节输入流，读取文件内容
            FileInputStream is = new FileInputStream(basePath+name);
            response.setContentType("image/jpeg");
            //字节输出流，将读取到文件回显到浏览器页面
            ServletOutputStream os = response.getOutputStream();
            int len = 0;
            byte[] buffer =new byte[1024];
            while((len = is.read(buffer)) != -1){
                os.write(buffer,0,len);
                os.flush();
            }
            is.close();
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
